<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class InvitationCode extends Model
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'invitation_code';


    /**
     * 检查邀请码是否正确
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-04-21
     * @param string $code
     * @return void
     */
    public function checkInvitationCode($code, $medical_id, $action = '')
    {
        $code = self::where('code', $code)->first();
        $memberId = memberId();
        if ($code) {
            if ($action == 'create') {
                if ($code['status'] == 1) {
                    return fail_message('邀请码已被使用');
                }
            } elseif ($action == 'edit') {
                if ($code['status'] == 1 && $code['user_id'] != $memberId && $code['fk_id'] != $medical_id) {
                    return fail_message('请勿使用他人邀请码');
                } elseif ($code['status'] == 1 && $code['user_id'] == $memberId && $code['fk_id'] != $medical_id) {
                    return fail_message('请勿重复使用邀请码');
                }
            }
            return true;
        } else {
            return fail_message('邀请码不正确');
        }
    }


    /**
     * 使用邀请码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-04-21
     * @param string $code
     * @return void
     */
    public function useInvitationCode($code, $fk_id)
    {
        $code = self::where('code', $code)->first();
        if (!empty($code)) {
            $code->user_id = memberId();
            $code->type = 'medical';
            $code->fk_id = $fk_id;
            $code->add_ip = request()->getClientIp();
            $code->status = 1;
            $code->use_time = Carbon::now();
            $code->save();
            return true;
        }
    }
}
